package controllers;

import java.util.Date;


import models.UserActions;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class UserActionsConnect {
	
	public UserActionsConnect(){
		
	}
	
	public static void AddAction(String user_Email, String page_Accessed, String action, String comments, String UserRole, Date lastLogin){
		
		if ( System.getProperty("USERACTION").equalsIgnoreCase("TRUE") )
		{
			Objectify ofy = ObjectifyService.begin();
			UserActions UACT = new UserActions();
			UACT.setUser_Email(user_Email);
			UACT.setPage_Accessed(page_Accessed);
			UACT.setAction(action);
			UACT.setComments(comments);
			UACT.setUserRole(UserRole);
			UACT.setLastLogin(lastLogin);
			ofy.put(UACT);
		}
	}
	
	public Date getLastLogin(String User_Email) {

		Objectify ofy = ObjectifyService.begin(); 
		
		try{
			//FIRST RECORD IS LASTEST LOGIN VALUE GET THE NEXT RECORD
			Query<UserActions> qry = ofy.query(UserActions.class).filter("User_Email", User_Email).filter("Action", "login").order("-LastLogin").limit(2);
    		
			int rowCount = 0;
			for ( UserActions uActions : qry.fetch() ) 
			{
				if ( rowCount == 1)
				{
					return uActions.getLastLogin();
				}
				rowCount++;
    		}    		
			
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
}
